package com.cloudweb.oa.config;

import com.redmoon.oa.db.SequenceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement // 注解事务管理，等同于xml配置方式的 <tx:annotation-driven />
public class TransactionConfig {

    @Autowired
    @Qualifier("transactionManager")
    private PlatformTransactionManager transactionManager;

    @PostConstruct
    public void init() {
        SequenceManager.setTransactionManager(transactionManager);
    }

    /**
     * 事务管理器
     * @param dataSource 加上@Qualifier("dataSource")可用于多数据源的情况
     * @return
     */
    @Bean
    @ConditionalOnProperty(name = "transaction.enabled", havingValue = "true")
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        PlatformTransactionManager platformTransactionManager = new DataSourceTransactionManager(dataSource);
        return platformTransactionManager;
    }

    @Bean
    public TransactionTemplate transactionTemplate() {
        TransactionTemplate template = new TransactionTemplate(transactionManager);
        // 设置默认的事务传播行为
        template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 设置默认的事务隔离级别
        template.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
        // 设置默认超时时间
        template.setTimeout(30);
        return template;
    }
}
